package com.tsj.spzx.service.Impl;

import cn.hutool.core.collection.CollectionUtil;
import com.tsj.spzx.exception.TsjException;
import com.tsj.spzx.mapper.SysRoleMenuMapper;
import com.tsj.spzx.model.dto.system.AssginMenuDto;
import com.tsj.spzx.model.entity.system.SysMenu;
import com.tsj.spzx.model.vo.common.ResultCodeEnum;
import com.tsj.spzx.service.SysMenuService;
import com.tsj.spzx.service.SysRoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysRoleMenuServiceImpl implements SysRoleMenuService {

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;
    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public Map<String, Object> findSysRoleMenuByRoleId(Integer roleId) {
        // 1、先查询所有的菜单信息
        List<SysMenu> sysMenuList = sysMenuService.findNodes();

        // 2、根据角色id查询到该角色已分配过的所有的菜单id
        List<Long> roleMenuIdList = sysRoleMenuMapper.findSysRoleMenuByRoleId(roleId);

        // 存放到map集合
        Map<String, Object> map = new HashMap<>();
        map.put("sysMenuList", sysMenuList);
        map.put("roleMenuIds", roleMenuIdList);

        return map;
    }

    @Transactional
    @Override
    public void doAssign(AssginMenuDto assginMenuDto) {
        // 为角色分配菜单
        // 1、删除该角色之前分配过的菜单
        sysRoleMenuMapper.deleteByRoleId(assginMenuDto.getRoleId());

        if (CollectionUtil.isEmpty(assginMenuDto.getMenuIdList())){
            throw new TsjException(ResultCodeEnum.DATA_ERROR);
        }
        // 2、重新分配菜单
        sysRoleMenuMapper.doAssign(assginMenuDto);
    }
}
